package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    /**
     * 新增菜品信息和口味
     *
     * @param dishDTO 菜品信息
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        //向菜品表插入一条数据
        dishMapper.insert(dish);

        Long id = dish.getId();
        //向口味表插入多条数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (!(flavors.isEmpty())) {
            //插入口味数据
            flavors.forEach(flavor -> {
                flavor.setDishId(id);
            });
            dishFlavorMapper.insertBatch(flavors);
        }

    }

    /**
     * 分页查询
     *
     * @param dishPageQueryDTO 分页查询参数
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        Page<DishVO> pages = dishMapper.pageQuery(dishPageQueryDTO);

        return new PageResult(pages.getTotal(), pages.getResult());
    }

    /**
     * 批量删除菜品
     *
     * @param ids ids
     */
    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        //判断，起售中的菜品不能删除
        ids.forEach(id -> {
            Dish dish = dishMapper.getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });

        //被套餐表关联的数据不能删除
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (!(setmealIds.isEmpty())) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //1.将dish菜品表中的数据删除
        //2.把口味表中的数据删除
        dishMapper.deleteByIds(ids);
        dishFlavorMapper.deleteByDishIds(ids);

    }

    /**
     * 禁止或启用菜品状态
     * @param status 状态
     */
    @Override
    public void startOrStop(Integer status,Long id) {
        Dish dish = new Dish();
        dish.setId(id);
        dish.setStatus(status);
        dishMapper.update(dish);
    }

    /**
     * 根据id查询菜品信息
     * @param id id
     * @return dishVO
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        //进行两次查表
        //查菜品表中的数据
        Dish dish = dishMapper.getById(id);

        //查口味表中的数据
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);

        //封装到dishVO对象中
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavors);

        return dishVO;
    }


    /**
     * 修改菜品信息和口味信息
     * @param dishDTO 菜品信息
     */
    @Override
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //修改菜品信息
        dishMapper.update(dish);
        //修改对应的口味信息，先删除 后添加
        List<Long> ids = new ArrayList<>();
        ids.add(dishDTO.getId());

        dishFlavorMapper.deleteByDishIds(ids);

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (!(flavors.isEmpty())) {
            // 遍历 flavors，设置 dishId 并过滤无效数据
            flavors.removeIf(flavor -> {
                if (flavor == null || flavor.getValue() == null || "[]".equals(flavor.getValue()) || "".equals(flavor.getValue().trim())) {
                    return true; // 移除无效的 flavor
                }
                flavor.setDishId(dishDTO.getId()); // 设置 dishId
                return false;
            });
        }
        dishFlavorMapper.insertBatch(flavors);
    }

    /**
     * 根据分类id查询菜品
     * @return list
     */
    @Override
    public List<Dish> getByCategoryId(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }

    /**
     * 根据条件查询菜品数据
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {

        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        dishList.forEach(d ->{
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查找口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());
            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        });

        return dishVOList;
    }
}
